package api

import (
	"api/common"
	"api/common/logger"
	"api/common/web"
	"fmt"
	"net/http"
	"net/smtp"
	"strings"
)

// @TagName 发送邮件
// @Controller MailController
type MailController struct{}

// @Title 发送邮件
// @Route /mail/send --> Send
// @Param {"mailTo":"", "title":"", "content":""}
// @Method post
func (this *MailController) Send(w http.ResponseWriter, r *http.Request) {
	defer web.PanicHandler(w, r)
	inputJson, jsonMsg := web.ExemptTokenCheckRequest(r)
	if jsonMsg != nil {
		web.ServeJSON(w, jsonMsg)
		return
	}

	mailToi := inputJson["mailTo"]
	titlei := inputJson["title"]
	contenti := inputJson["content"]

	if mailToi == nil || mailToi == "" {
		web.ServeJSON(w, web.JsonMsg{false, "收件人不能为空", 1})
		return
	}
	if titlei == nil || titlei == "" {
		web.ServeJSON(w, web.JsonMsg{false, "邮件标题不能为空", 1})
		return
	}
	if contenti == nil || contenti == "" {
		web.ServeJSON(w, web.JsonMsg{false, "邮件正文不能为空", 1})
		return
	}

	mailTo := common.ToStr(mailToi)
	title := common.ToStr(titlei)
	content := common.ToStr(contenti)

	e_user := "15234579277@139.com"
	e_paswd := "FEVERfever12"
	e_host := "smtp.139.com"
	e_port := "25"
	auth := smtp.PlainAuth("anda", e_user, e_paswd, e_host)

	to := strings.Split(mailTo, ";")
	msg := "To: %s\r\nSubject: %s\r\n\r\n%s\r\n"
	msg = fmt.Sprintf(msg, mailTo, title, content)
	err := smtp.SendMail(e_host+":"+e_port, auth, e_user, to, []byte(msg))
	if err != nil {
		logger.Error("发邮件错误：", err)
		web.ServeJSON(w, web.JsonMsg{false, "发邮件错误：" + err.Error(), 1})
		return
	}

	web.ServeJSON(w, web.JsonMsg{true, "发邮件成功！", 0})
}
